# -*- coding: utf-8 -*-

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
import json

# 执行api调用并存储响应数据
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
request = requests.get(url)

print("Status code",request.status_code)
filename = 'pythonProjectByStart.json'

# 响应信息
response_dict = {}

# 如果请求成功了，存储到本地文件中
if request.status_code == 200:
    with open(filename, 'w') as file_object:
        json.dump(request.json(), file_object)
        response_dict = request.json()

        print("我存下来这次的数据了")
else:#如果请求没成功，尝试从本地获取缓存的文件数据
    print("下载失败，从本地获取数据")
    # 从本地读取
    try:
        with open(filename) as file:
            response_dict = json.load(file)
    except FileNotFoundError as e:
        print("网络请求失败了，文件还不存在")
    else:
        print("本地读取到了数据")
# 处理结果
# print(response_dict.keys())

repo_dicts = response_dict['items']
names,start = [],[]
plot_dicts = []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    start.append(repo_dict['stargazers_count'])
    plot_dict = {
        'value' : repo_dict['stargazers_count'],
        'label' : repo_dict['description'],
    }
    plot_dicts.append(plot_dict)
# 可视化
my_style = LS('#336699',base_style=LCS)

# 创建一个配置对象，用来配置pygal对象
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000


chart = pygal.Bar(my_config,style = my_style)
chart.title = 'Most starred Python Projects on Github'
chart.x_labels = names
chart.y_title = 'stars'

chart.add('',plot_dicts)
chart.render_to_file('python_repos5.svg')